package com.naiterui.ehp.bs.cms.modules.security.utils;

import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RsaUtil {

    /**
     * 私钥
     */
    private static final String PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCX2pUG8IUTNw6T\n" +
            "rNHJ26/8DGoj07TN+LImV7XQGRimLUziPqXXEcnU3b4fo1nGsLwTHmEs3laeAAJb\n" +
            "S1+liwGN75aINKYQ0fKOnaEQ83Sg2btW6LViy6RYV4xthsMp8HDJiemdcOthO1FS\n" +
            "6JLjLyTYqAg4SfKxKA66oXKQMC+J/yqumfdPYRNBwBHSJOregbjHQxyC5nsYcYFW\n" +
            "t9QZe6DLNC3MZh3Y/2UsLB9e2eRm06MmAEtXD2+Xr3//nKbYqynBJNIRHi4jYa8v\n" +
            "ZtWGyWfAm4+SyW8Hv+scnJg31kY2JBUiRr11qV2v6molI3kyrjXGBtgbKNL7s7iv\n" +
            "LSOqp6TJAgMBAAECggEAQ91bJtvNDVZYvGTK6SS2VLWTpelSb47Kx1oBljvxCStL\n" +
            "pf0Ljr+TbP+gnXEaiTKpCv5TvYKsQTaN1xErcMdb7Xv60Wp+IRxDA7uspO+42r4T\n" +
            "/HZJwhpym0ydJMHKbO7Y6Skqb8NsXmrtIFlyc/e4xt7ptYZO4R+e3YeTtJ7kUA46\n" +
            "Xrn/zC5dHi6IdpPN9tWyl9cMW6My4eFCLXRryp9N8Hpq0hcPGluB9J6NEsgTFZjE\n" +
            "0bZM8yyQzPeQCaQ6r9WNgp0+YfRGOcbV1FOzs3tDJU+E6xLYLnVaJ5phMNmnY7aX\n" +
            "4Il32eCR9FkLauDp8nCrVQt6wXYIMoISlA6zFtIwNQKBgQDG2ZcnBozi3KYwhxMN\n" +
            "MxbAddQFubl7MKcLLu4jwovTz2HetVQG2uPBZcb2kea6BwbNNe6Xm0yYg1t2qF5I\n" +
            "IqXQ47o89/McJDd3DKQcAPrHN2v8d9e+WSgXOftztC48hE+iDewG9c7/PrlyGG6K\n" +
            "ELmPHYapchkjyisZajeygcAShwKBgQDDfz8Dcx9l9ehghwkwy3RlsRoGX7wGO5xh\n" +
            "l3E5aE/cydKlr7crbJmNamxhtzhAYHuxtEq8l5amA7Ej244Cp9v1Ow4m3s+gNDXb\n" +
            "Ntvul+H9ksSxqmCjvlI/gdmklilOuUkhO4R2eO1GqzOuOC3VgKCPkX9WECGCWZ+4\n" +
            "9N4GZiNSLwKBgQCyzNqmI7SxFPh2cC6IUuTlX82q7EpE5AV//83v57H1XedB60hH\n" +
            "9bCPqOWTtrOBmGncQd9tAR6JkKvAcTp9oHH695nx0n4OUt5wtLQn3hWg5ku6M0SS\n" +
            "CvcKk39vlZdxoQM900jlJUfgqVT0q9VRXiKL9l+so0TJsrK4YpL8dsDvpwKBgQCL\n" +
            "3G8SYrwlz8XNuQ3kMMo3Lnq18KutsdvxHc1NCsmH5YOkMY/Tq0A3odmkFtZRiDU2\n" +
            "LwwA3FpUrvN9+cchM0HzsaowONtFe9TD3f1+Nn7hUK0ThhbZToG9GYLBcwReY8Rj\n" +
            "2BauQ1lNY5H3pA12Xy1/SNJWmfe/L6tLQTPOVCgU1QKBgCn6KcfSvDnS1Yej3h+s\n" +
            "Ub9TRd6f+qTd4UeWZ7rMnoxEOkN/U3QNd0cJ1flhWlqam8HYm5gvRRmg3bJVd/gu\n" +
            "Yu3QfWDA5wBQHltmlTQI7BAq6VhKzK0pmpPVZiGaQyejfeh/qrCI0wqBwI7p0Pw1\n" +
            "k7wLd/nVTN+AmBjrb6Ue7ApE";

    /**
     * 公钥
     */
    private static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl9qVBvCFEzcOk6zRyduv\n" +
            "/AxqI9O0zfiyJle10BkYpi1M4j6l1xHJ1N2+H6NZxrC8Ex5hLN5WngACW0tfpYsB\n" +
            "je+WiDSmENHyjp2hEPN0oNm7Vui1YsukWFeMbYbDKfBwyYnpnXDrYTtRUuiS4y8k\n" +
            "2KgIOEnysSgOuqFykDAvif8qrpn3T2ETQcAR0iTq3oG4x0McguZ7GHGBVrfUGXug\n" +
            "yzQtzGYd2P9lLCwfXtnkZtOjJgBLVw9vl69//5ym2KspwSTSER4uI2GvL2bVhsln\n" +
            "wJuPkslvB7/rHJyYN9ZGNiQVIka9daldr+pqJSN5Mq41xgbYGyjS+7O4ry0jqqek\n" +
            "yQIDAQAB";

    public static String encryptData(String data) {
        return RsaUtil.encryptData(data, PUBLIC_KEY);
    }

    /**
     * RSA加密
     */
    @SuppressWarnings("WeakerAccess")
    public static String encryptData(String data, String publicKey) {
        try {
            //base64编码的公钥
            byte[] decoded = Base64.decodeBase64(publicKey);
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            byte[] dataToEncrypt = data.getBytes(Charsets.UTF_8);
            byte[] encryptedData = cipher.doFinal(dataToEncrypt);
            return Base64.encodeBase64String(encryptedData);
        } catch (Exception e) {
            log.warn("RSA加密失败 data:{}", data, e);
        }
        return null;
    }

    public static String decryptData(String data) {
        return decryptData(data, PRIVATE_KEY);
    }

    /**
     * RSA解密
     */
    @SuppressWarnings("WeakerAccess")
    public static String decryptData(String data, String privateKey) {
        try {
            byte[] decoded = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            byte[] descryptData = Base64.decodeBase64(data);
            byte[] descryptedData = cipher.doFinal(descryptData);
            return new String(descryptedData, Charsets.UTF_8);
        } catch (Exception e) {
            log.warn("RSA解密失败 data:{}", data, e);
        }
        return null;
    }

}